<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>购物车</title>
    <script src="js/vue.js"></script>
</head>

<body>
    <div id="app">
        <!-- 写入组件 -->
        <div>
            <input type="text" v-model="product.name" placeholder="请输入商品名称">
            <input type="text" v-model="product.price" placeholder="请输入商品单价">
            <input type="number" v-model="product.count">
            <button @click="addCart">加入购物车</button>
        </div>
        <!-- 购物车列表 -->
        <div>
            <h3>购物车列表</h3>
            <table border="1" width="500">
                <thead>
                    <tr>
                        <th>商品名字</th>
                        <th>单价</th>
                        <th>数量</th>
                        <th>小计</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="(item,index) in carts">
                        <td>{{item.name}}</td>
                        <td>{{item.price}}</td>
                        <td>{{item.count}}</td>
                        <td>{{item.price * item.count}}</td>
                        <td><button @click="carts.splice(index,1)">删除</button></td>
                    </tr>
                </tbody>
            </table>
            <h3>总价:{{total()}}</h3>
        </div>
    </div>
</body>

</html>
<script>
    new Vue({
        el: "#app",
        data: {
            // 存放购物车数据
            carts: [],
            // 商品
            product: {
                // id:1,
                // name:"商品1",
                // price:100,
                // count:1
            }
        },
        methods: {
            total() {
                // reduce方法 累加 pre累加项
                return this.carts.reduce((pre, item) => pre + item.price * item.count, 0)
            },
            addCart() {
                //判断购物车中是否存在此商品
                let index = this.carts.findIndex(item => item.name === this.product.name)
                if (index === -1) {
                    // 购物车中没有此商品
                    this.carts.push({
                        name: this.product.name,
                        price: parseFloat(this.product.price),
                        count: parseInt(this.product.count)
                    })
                } else {
                    // 购物车中有此商品,修改数量
                    this.carts[index].count += parseInt(this.product.count) || 0

                }
                this.product = {}
            }
        }
    })
</script>